﻿using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace RabbitBus
{
    /// <summary>
    /// 创建连接对象
    /// </summary>
    public class CreateConnectionFactory
    {
        public ConnectionFactory ConnectionFactory { get; set; }

        public static ConnectionFactory CreateRabbitMqConnectionFactory()
        {
            var factory = new ConnectionFactory();
            //factory.UseBackgroundThreadsForIO = false;
            factory.AutomaticRecoveryEnabled = true; //设置端口异常后自动恢复连接属性
            //factory.TopologyRecoveryEnabled = false;

            //factory.VirtualHost = ""; //虚拟机
            factory.HostName = "127.0.0.1";
            factory.UserName = "guest";
            factory.Password = "guest";
            factory.Port = AmqpTcpEndpoint.UseDefaultPort;//端口号，不配置使用默认
            //factory.Ssl = new SslOption();
            return factory;
        }


        /// <summary>
        /// 根据Queue的名字查找相应的消费Class
        /// </summary>
        /// <param name="queueName"></param>
        /// <returns></returns>
        private List<Type> GetQueueConsumers(string queueName)
        {
            var result = new List<Type>();
            var consumers = Assembly.GetAssembly(typeof(IConsumer)).GetTypes().Where(x => x.IsGenericType).ToList();
            foreach (var consumer in consumers)
            {
                var attributions = consumer.GetCustomAttributes(typeof(QueueConsumerAttribute), false);
                if (attributions.Length <= 0)
                {
                    result.Add(consumer);
                    continue;
                }
                var attribution = attributions[0] as QueueConsumerAttribute;
                if (attribution == null || attribution.QueueName.Equals(queueName, StringComparison.OrdinalIgnoreCase))
                {
                    result.Add(consumer);
                }
            }
            return result;
        }
    }
}
